/*
 * @Author: hrg
 * @Date: 2024-01-31 16:08:52
 * @LastEditTime: 2024-02-01 08:59:48
 * @FilePath: \study_go\study09_gin\gin_dome_02\main.go
 * @Description:  cookie练习
 */

//  模拟实现权限验证中间件
// 有2个路由，login和home
// login用于设置cookie
// home是访问查看信息的请求
// 在请求home之前，先跑中间件代码，检验是否存在cookie
package main

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	// 创建路由
	r := gin.New()

	// 服务端要给客户端cookie
	r.GET("/login", Login)
	r.GET("/home", homeMiddleWare, Home)

	r.Run(":9090")

}

func Login(c *gin.Context) {
	// 获取客户端是否携带token
	cookie, err := c.Cookie("cookie_key")

	if err != nil {
		cookie = "NotSet"

		c.SetCookie("cookie_key", "asdfghjkl", 60, "/",
			"localhost", false, true)
	}
	fmt.Printf("cookie的值是： %s\n", cookie)

	c.JSON(http.StatusOK, gin.H{
		"cookie": cookie,
	})
}

// 访问查看信息的请求
func Home(c *gin.Context) {
	c.JSON(200, gin.H{
		"success": "查看访问信息的请求",
	})
}

// 定义home的中间件
func homeMiddleWare(c *gin.Context) {
	cookie, err := c.Cookie("cookie_key")
	if err != nil || cookie != "asdfghjkl" {
		c.JSON(200, gin.H{
			"error": "cookie is error",
		})
		return
	}

	c.Next()

	fmt.Println("中间件继续执行")

}
